import 'package:get/get.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/page/detection/view.dart';
import 'package:sgy_flutter/widget/app_dialog.dart';
import 'package:webview_flutter/webview_flutter.dart';

class QuestionLogic extends GetxController {
  static const detectionUrl = "sgy://detection";

  late WebViewController controller;

  var loading = true.obs;

  @override
  void onInit() {
    super.onInit();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {
            loading(true);
          },
          onPageFinished: (String url) {
            loading(false);
          },
          onHttpError: (HttpResponseError error) {
            loading(false);
          },
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            printError(info: "request.url:${request.url}");
            if (request.url.startsWith(detectionUrl)) {
              showDetectionDialog();
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
        ),
      );
  }

  String deviceType() {
    final name = bleManager.deviceModel?.name ?? '';
    if (name.contains("AXOCC") || name.contains("AXOcc")) {
      return "AXOcc";
    }
    if (name.contains("AXO") || name.contains("SPM2")) {
      return "AXO";
    }
    if (name.contains("DLS_L")) {
      return "DLS_L";
    }
    if (name.contains("DLS_R")) {
      return "DLS_R";
    }
    if (name.contains("AXPOWER")) {
      return "AXPOWER";
    }
    if (name.contains("HIFLOW")) {
      return "HIFLOW";
    }
    return "";
  }

  @override
  void onReady() async {
    final resp = await apiService.getQuestion(deviceType());
    final html = """
    <!-- 使用Ctrl+/进行快捷注释，使用下面的代码进行文档声明 -->
<!DOCTYPE html>
<!-- 使用下面的代码定义language为English -->
<html lang="en">
<!-- 定义编码格式、标题等 -->
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    ${resp.data}
</body>
</html>
    """;
    controller.loadHtmlString(html);
    super.onReady();
  }

  void showDetectionDialog() async {
    final result = await Get.dialog(AppDialog(
      title: "提示".tr,
      message: "您的设备是否出现异常?".tr,
      submit: "是".tr,
      cancel: "否".tr,
      onSubmit: () => Get.backLegacy(result: true),
    ), barrierDismissible: false);
    if (result == true) {
      checkDeviceVersion();
    }
  }

  /// 需要判断是否充电中,旧的设备根据有没有服务,充电中没有这个蓝牙服务
  void checkDeviceVersion() async {
    if (await bleManager.ensureDeviceConnected()) {
      final notService = bleManager.oldService.writeCharacteristic == null;
      if (notService) {
        final firmwareVersion = bleManager.deviceModel?.firmwareNumber ?? 0;

        final deviceType = this.deviceType();
        if (deviceType == "AXO") {
          if (firmwareVersion <= 4.015) {
            Get.dialog(
                AppDialog(
                    title: "提示".tr,
                    message: "请先升级固件".tr,
                    submit: "好的，我知道了！".tr),
                barrierDismissible: false);
          } else {
            Get.dialog(
                AppDialog(
                  title: "提示".tr,
                  message: "请先移除充电线并重新连接".tr,
                  submit: "好的，我知道了！".tr,
                  onSubmit: () => Get.back(),
                ),
                barrierDismissible: false);
          }
        } else if (deviceType == "DLS_L" || deviceType == "DLS_R") {
          if (firmwareVersion <= 4.4) {
            Get.dialog(
                AppDialog(
                    title: "提示".tr,
                    message: "请先升级固件".tr,
                    submit: "好的，我知道了！".tr),
                barrierDismissible: false);
          } else {
            Get.dialog(
                AppDialog(
                  title: "提示".tr,
                  message: "请先移除充电线并重新连接".tr,
                  submit: "好的，我知道了！".tr,
                  onSubmit: () => Get.back(),
                ),
                barrierDismissible: false);
          }
        } else {
          Get.dialog(
              AppDialog(
                  title: "提示".tr,
                  message: "设备不支持诊断,请先升级固件".tr,
                  submit: "好的，我知道了！".tr),
              barrierDismissible: false);
        }
      } else {
        //有服务的设备
        try {
          if (bleManager.deviceModel?.isDoubleSlide == true || rightBleManager.deviceModel?.isDoubleSlide == true ) {
            bool? isLeftCharging;
            try{
              isLeftCharging = await bleManager.isCharging();
            }catch(e){
              printError(info: "$e");
            }
            bool? isRightCharging;
            try{
              isRightCharging = await rightBleManager.isCharging();
            }catch(e){
              printError(info: "$e");
            }

            if (isLeftCharging == true || isRightCharging == true) {
              Get.dialog(
                  AppDialog(
                      title: "提示".tr,
                      message: "请先停止给设备充电，然后再进行检测".tr,
                      submit: "好的，我知道了！".tr),
                  barrierDismissible: false);
            } else {
              Get.to(() => DetectionPage());
            }
          } else {
            final isCharging = await bleManager.isCharging();
            if (isCharging) {
              Get.dialog(
                  AppDialog(
                      title: "提示".tr,
                      message: "请先停止给设备充电，然后再进行检测".tr,
                      submit: "好的，我知道了！".tr),
                  barrierDismissible: false);
            } else {
              Get.to(() => DetectionPage());
            }
          }
        } catch (e) {
          printError(info: "$e");
          Get.dialog(
              AppDialog(
                  title: "提示".tr,
                  message: "请先停止给设备充电，然后再进行检测".tr,
                  submit: "好的，我知道了！".tr),
              barrierDismissible: false);
        }
      }
    }
  }
}
